// API配置文件

// 后端服务的基础URL配置
export const API_BASE_URL = 'http://localhost:5000';

// API路径配置
export const API_PATHS = {
  // 用户相关
  LOGIN: '/api/auth/login',
  REGISTER: '/api/auth/register',
  USERS: '/api/users',

  // 电影相关
  MOVIES: '/api/movies',
  MOVIE_DETAIL: (id: string) => `/api/movies/${id}`,
  MOVIE_ORDERS: (id: string) => `/api/movies/${id}/orders`,

  // 订单相关
  ORDERS: '/api/orders',
  ORDER_DETAIL: (id: string) => `/api/orders/${id}`,
  CANCEL_ORDER: (id: string) => `/api/orders/${id}/cancel`,
};

// 通用请求头配置
const getHeaders = () => {
  const token = localStorage.getItem('token');
  return {
    'Content-Type': 'application/json',
    ...(token ? { 'Authorization': `Bearer ${token}` } : {}),
  };
};

// 统一的API请求函数
export const apiRequest = async <T>(
  path: string,
  options: RequestInit = {}
): Promise<T> => {
  const url = `${API_BASE_URL}${path}`;
  const headers = getHeaders();

  const response = await fetch(url, {
    ...options,
    headers: {
      ...headers,
      ...options.headers,
    },
  });

  const data = await response.json();

  if (!response.ok) {
    throw new Error(data.message || '请求失败');
  }

  return data;
};